package com.wish.service.impl;

import com.wish.entity.TCwPaymentPlan;
import com.wish.entity.TSfContract;
import com.wish.mapper.TCwPaymentPlanMapper;
import com.wish.mapper.TSfContractMapper;
import com.wish.service.ITCwPaymentPlanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wish.util.MyJinRongUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 五组
 * @since 2021-04-16
 */
@Service

@Slf4j
public class TCwPaymentPlanServiceImpl extends ServiceImpl<TCwPaymentPlanMapper, TCwPaymentPlan> implements ITCwPaymentPlanService {

    @Resource
    private TCwPaymentPlanMapper cwPaymentPlanMapper;

    @Resource
    private TSfContractMapper tSfContractMapper;

    @Override
    @Transactional
    public TSfContract getPlans(Integer id) {


        TSfContract contract = tSfContractMapper.getOneById(id);
        List<TCwPaymentPlan> payList = cwPaymentPlanMapper.getPlans(id);
        double balance = 0;
        Date startDate = null;
        if (payList.size() > 0) {
            for (TCwPaymentPlan r : payList) {
                balance = MyJinRongUtils.add(balance, r.getPaymentAmount().doubleValue());
                if (null == startDate) {
                    startDate = r.getPaymentDaysBegin();
                } else if (1 == startDate.compareTo(r.getPaymentDaysBegin())) {
                    startDate = r.getPaymentDaysBegin();
                }
            }
        }

        Date endDate = contract.getLeaseEndTime();
        List<MyJinRongUtils.KeyValueForDate> splitMonth = MyJinRongUtils.getSplitMonthForDate(startDate, endDate);
        double div = MyJinRongUtils.div(balance, splitMonth.size(), 2);
        balance = MyJinRongUtils.sub(balance, div);
        contract.setBalance(balance);
        return contract;
    }


}
